package com.lianyu.wangyiyun.activity;

import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.lianyu.wangyiyun.R;
import com.lianyu.wangyiyun.databinding.ActivityMainBinding;
import com.lianyu.wangyiyun.fragment.MainFragment;
import com.lianyu.wangyiyun.fragment.MusicDialogFragment;
import com.lianyu.wangyiyun.model.Mp3Info;
import com.lianyu.wangyiyun.model.MusicListViewModel;
import com.lianyu.wangyiyun.service.MusicService;
import com.lianyu.wangyiyun.utils.HistoryHelper;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author Chen Yuguang
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    /**
     * 更新播放进度的handler信号值
     */
    public static final int UPDATE_PROGRESS = 1;
    /**
     * 循环模式-列表循环
     */
    public static final int LIST_XUN = 0;
    /**
     * 循环模式-单曲循环
     */
    public static final int ONE_XUN = 1;
    /**
     * 循环模式-随机循环
     */
    public static final int SUI_XUN = 2;
    /**
     * 发送播放开始的广播动作值
     */
    public static final String ACTION_MUSIC_START = "com.lianyu.wangyiyun.ACTION_MUSIC_START";
    /**
     * 发送更新暂停/播放状态的广播动作值
     */
    public static final String ACTION_MUSIC_PLAY = "com.lianyu.wangyiyun.ACTION_MUSIC_PLAY";
    /**
     * 发送更新播放位置的广播动作值
     */
    public static final String ACTION_MUSIC_MAIN_POSITION = "com.lianyu.wangyiyun.ACTION_MUSIC_MAIN_POSITION";
    /**
     * 发送播放上一首的广播动作值
     */
    public static final String ACTION_MUSIC_LAST = "com.lianyu.wangyiyun.ACTION_MUSIC_LAST";
    /**
     * 发送播放下一首的广播动作值
     */
    public static final String ACTION_MUSIC_NEXT = "com.lianyu.wangyiyun.ACTION_MUSIC_NEXT";
    /**
     * 发送播放切换模式的广播动作值
     */
    public static final String ACTION_MUSIC_SWITCH = "com.lianyu.wangyiyun.ACTION_MUSIC_SWITCH";
    private ActivityMainBinding activityMainBinding;
    private MusicService mService;
    private MusicListViewModel mainMusicListViewModel;
    /**
     * 随机播放储存乱序position的列表
     */
    private final List<Integer> positions = new ArrayList<>();
    /**
     * 随机播放position哈希表，用来查找当前播放位置处于乱序position列表的哪个位置
     */
    private final Map<Integer, Integer> randomMap = new HashMap<>();

    /**
     * 旋转动画
     */
    private ObjectAnimator objectAnimator;

    /**
     * 单线程化的定时线程池
     */
    private final ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor();
    /**
     * 单线程的任务
     */
    private ScheduledFuture<?> future;

    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == UPDATE_PROGRESS) {
                int position = msg.arg1;
                activityMainBinding.progress.setProgress(position);
            }
        }
    };

    private class MusicProgressRunnable implements Runnable {
        @Override
        public void run() {
            if (mService != null && mService.isNotInitialized()) {
                int position = mService.getCurrentPosition();
                Message message = new Message();
                message.what = UPDATE_PROGRESS;
                message.arg1 = position;
                mHandler.sendMessage(message);
            }
        }
    }

    public class MusicReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Integer position, mode;
            switch (intent.getAction()) {
                case ACTION_MUSIC_START:
                    //开始播放
                    start();
                    //同步当前播放位置
                    position = mainMusicListViewModel.getPositionLiveData().getValue();
                    if (position != null) {
                        Intent newIntent = new Intent(PlayerActivity.ACTION_MUSIC_PLAYER_POSITION);
                        newIntent.putExtra("position", position);
                        sendBroadcast(newIntent);
                    }
                    break;
                case ACTION_MUSIC_PLAY:
                    //更新播放/暂停状态
                    updateSta();
                    break;
                case ACTION_MUSIC_MAIN_POSITION:
                    //更新当前播放位置
                    position = intent.getIntExtra("position", -1);
                    if (position != -1) {
                        mainMusicListViewModel.getPositionLiveData().setValue(position);
                    }
                    Intent serviceIntent = new Intent(context,MusicService.class);
                    List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
                    if (mp3Infos != null) {
                        Mp3Info mp3Info = mp3Infos.get(position);
                        //传送url给service播放
                        serviceIntent.putExtra("url", mp3Info.getUrl());
                        serviceIntent.putExtra("title", mp3Info.getTitle());
                        serviceIntent.putExtra("artist", mp3Info.getArtist());
                        context.startService(serviceIntent);
                    }
                    break;
                case ACTION_MUSIC_LAST:
                    //上一首（考虑播放模式）
                    lastMode();
                    break;
                case ACTION_MUSIC_NEXT:
                    //下一首（考虑播放模式）
                    nextMode();
                    break;
                case ACTION_MUSIC_SWITCH:
                    //切换播放模式
                    switchMode();
                    //同步模式值
                    mode = mainMusicListViewModel.getModeLiveData().getValue();
                    if (mode != null) {
                        Intent newIntent = new Intent(PlayerActivity.ACTION_MUSIC_PLAYER_MODE);
                        newIntent.putExtra("mode", mode);
                        sendBroadcast(newIntent);
                    }
                    break;
                default:
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //绑定服务
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, mConn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        //解绑服务
        unbindService(mConn);
        super.onStop();
    }

    private final ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MusicService.MusicServiceBinder binder = (MusicService.MusicServiceBinder) iBinder;
            mService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mService = null;
        }
    };

    @Override
    protected void initData() {
        mainMusicListViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MusicListViewModel.class);
        mainMusicListViewModel.getMusicLiveData().observe(this, mp3Infos -> {
            //播放列表长度
            int size = mp3Infos.size();
            //乱序position列表或哈希表为空则重新生成
            if (positions.isEmpty() || randomMap.isEmpty()) {
                positions.clear();
                randomMap.clear();
                for (int i = 0; i < size; i++) {
                    positions.add(i);
                }
                //将列表乱序
                Collections.shuffle(positions);
                //将 播放列表位置—乱序中的位置 信息储存到position哈希表中
                for (int i = 0; i < size; i++) {
                    randomMap.put(positions.get(i), i);
                }
            }
        });
    }

    @Override
    protected void initView() {
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        //初始化为暂停状态
        activityMainBinding.progress.setStatus(1);
        //初始化进度为0
        activityMainBinding.progress.setProgress(0);
        //设置点击事件
        activityMainBinding.progress.setOnClickListener(this);
        activityMainBinding.list.setOnClickListener(this);
        activityMainBinding.bottomBar.setOnClickListener(this);
        //显示主fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragmentContainer, new MainFragment(), "main");
        transaction.commit();
    }

    @Override
    protected void initEvent() {
        //新建广播接收者
        MusicReceiver musicReceiver = new MusicReceiver();
        //新建广播过滤器
        IntentFilter intentFilter = new IntentFilter();
        //给过滤器添加动作
        intentFilter.addAction(ACTION_MUSIC_START);
        intentFilter.addAction(ACTION_MUSIC_PLAY);
        intentFilter.addAction(ACTION_MUSIC_MAIN_POSITION);
        intentFilter.addAction(ACTION_MUSIC_LAST);
        intentFilter.addAction(ACTION_MUSIC_NEXT);
        intentFilter.addAction(ACTION_MUSIC_SWITCH);
        //注册广播接收者
        registerReceiver(musicReceiver, intentFilter);
        //旋转动画
        objectAnimator = ObjectAnimator.ofFloat(activityMainBinding.circleImage, "rotation", 0, 360);
        objectAnimator.setDuration(50000);
        //动画的反复次数
        objectAnimator.setRepeatCount(-1);
        //匀速插值器
        objectAnimator.setInterpolator(new LinearInterpolator());
    }

    @Override
    public void onClick(View v) {
        List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
        //判断播放列表是否为空
        if (mp3Infos != null) {
            //点击播放/暂停按钮
            if (v == activityMainBinding.progress) {
                play();
                //点击列表按钮
            } else if (v == activityMainBinding.list) {
                MusicDialogFragment musicDialogFragment = new MusicDialogFragment();
                musicDialogFragment.show(getSupportFragmentManager(), "dialog");
                v.setClickable(false);
                //避免短时间内二次点击
                new Handler(Looper.myLooper()).postDelayed(() -> v.setClickable(true), 2000);
                //点击其它区域跳转PlayerActivity
            } else if (v == activityMainBinding.bottomBar) {
                Intent intent = new Intent(this, PlayerActivity.class);
                intent.putExtra("mp3Infos", (Serializable) mp3Infos);
                Integer mode = mainMusicListViewModel.getModeLiveData().getValue();
                if (mode != null) {
                    intent.putExtra("mode", mode);
                }
                Integer position = mainMusicListViewModel.getPositionLiveData().getValue();
                if (position != null) {
                    intent.putExtra("position", position);
                }
                if (mService != null) {
                    intent.putExtra("isPlaying", mService.isPlaying());
                    intent.putExtra("duration", mService.getDuration());
                    intent.putExtra("currentPosition", mService.getCurrentPosition());
                }
                startActivity(intent);
                overridePendingTransition(R.anim.bottom_in, 0);
            }
        } else {
            Toast.makeText(this, "请先从列表选择音乐进行播放", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        //searchFragment的标签
        String search = "search";
        Fragment searchFragment = getSupportFragmentManager().findFragmentByTag(search);
        if (searchFragment == null) {
            super.onBackPressed();
        } else {
            //如果当前显示的fragment为searchFragment则移除searchFragment
            //新建事务
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            //移除searchFragment
            transaction.remove(searchFragment);
            Fragment mainFragment = getSupportFragmentManager().findFragmentByTag("main");
            if (mainFragment != null) {
                //显示主fragment
                transaction.show(mainFragment);
                //提交事务
                transaction.commit();
            }
        }

    }

    /**
     * 开始播放音乐
     */
    private void start() {
        if (mService != null) {
            //设置总进度
            activityMainBinding.progress.setmTotalProgress(mService.getDuration());
            //开启进度监听线程
            if (future == null) {
                future = scheduled.scheduleWithFixedDelay(new MusicProgressRunnable(), 0, 100L, TimeUnit.MILLISECONDS);
            }
            //设置播放状态
            activityMainBinding.progress.setStatus(0);
            //取得viewModel播放列表
            List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
            if (mp3Infos != null) {
                //取得viewModel当前播放位置
                Integer position = mainMusicListViewModel.getPositionLiveData().getValue();
                if (position != null) {
                    //取得音乐信息
                    Mp3Info mp3Info = mp3Infos.get(position);
                    //保存音乐信息到播放记录
                    HistoryHelper.writeHistory(mp3Info);
                    //获取主fragment
                    Fragment mainFragment = getSupportFragmentManager().findFragmentByTag("main");
                    if (mainFragment != null) {
                        //刷新主fragment的历史记录
                        ((MainFragment) mainFragment).refreshHistory();
                    }
                    String title = mp3Info.getTitle();
                    String artist = mp3Info.getArtist();
                    String url = mp3Info.getUrl();
                    String album = mp3Info.getAlbum();
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
                    SpannableString spannableString = new SpannableString(" - " + artist);
                    //设置大小
                    RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(0.75f);
                    //设置颜色
                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.GRAY);
                    spannableString.setSpan(relativeSizeSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(foregroundColorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(title);
                    spannableStringBuilder.append(spannableString);
                    activityMainBinding.title.setText(spannableStringBuilder);
                    String http = "http";
                    if (new File(url).isFile()) {
                        //取本地专辑图
                        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                        mediaMetadataRetriever.setDataSource(url);
                        byte[] data = mediaMetadataRetriever.getEmbeddedPicture();
                        Bitmap albumPicture = null;
                        if (data != null) {
                            //获取bitmap对象
                            albumPicture = BitmapFactory.decodeByteArray(data, 0, data.length);
                        }
                        if (albumPicture != null) {
                            Glide.with(this).load(albumPicture).placeholder(R.drawable.cd).into(activityMainBinding.circleImage);
                        } else {
                            activityMainBinding.circleImage.setImageResource(R.drawable.cd);
                        }
                    } else if (url.startsWith(http)) {
                        //加载网络专辑图
                        if (album.isEmpty()) {
                            activityMainBinding.circleImage.setImageResource(R.drawable.cd);
                        } else {
                            Glide.with(this).load(album).placeholder(R.drawable.cd).into(activityMainBinding.circleImage);
                        }
                    } else {
                        activityMainBinding.circleImage.setImageResource(R.drawable.cd);
                    }
                    //开启旋转动画
                    if (objectAnimator != null) {
                        objectAnimator.start();
                    }
                }
            }
        }
    }

    /**
     * 播放/暂停音乐
     */
    private void play() {
        if (mService != null) {
            if (mService.isPlaying()) {
                //设置暂停状态
                activityMainBinding.progress.setStatus(1);
                mService.pause();
                //暂停旋转动画
                if (objectAnimator != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        objectAnimator.pause();
                    } else {
                        objectAnimator.cancel();
                    }
                }
                //取消进度监听任务
                if (future != null) {
                    future.cancel(true);
                    future = null;
                }
            } else {
                //设置播放状态
                activityMainBinding.progress.setStatus(0);
                mService.play();
                //继续旋转动画
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    objectAnimator.resume();
                } else {
                    objectAnimator.start();
                }
                //重开进度监听任务
                if (future == null) {
                    future = scheduled.scheduleWithFixedDelay(new MusicProgressRunnable(), 0, 100L, TimeUnit.MILLISECONDS);
                }
            }
        }
    }

    /**
     * 更新播放/暂停状态
     */
    private void updateSta() {
        if (mService != null) {
            if (mService.isPlaying()) {
                //设置播放状态
                activityMainBinding.progress.setStatus(0);
                //继续旋转动画
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    objectAnimator.resume();
                } else {
                    objectAnimator.start();
                }
                //重开进度监听任务
                if (future == null) {
                    future = scheduled.scheduleWithFixedDelay(new MusicProgressRunnable(), 0, 100L, TimeUnit.MILLISECONDS);
                }
            } else {
                //设置暂停状态
                activityMainBinding.progress.setStatus(1);
                //暂停旋转动画
                if (objectAnimator != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        objectAnimator.pause();
                    } else {
                        objectAnimator.cancel();
                    }
                }
                //取消进度监听任务
                if (future != null) {
                    future.cancel(true);
                    future = null;
                }
            }
        }
    }

    /**
     * 播放上一首音乐
     */
    private void last() {
        //获取mainActivity的viewModel值（播放的位置）
        Integer oldPosition = mainMusicListViewModel.getPositionLiveData().getValue();
        if (oldPosition != null) {
            //获取mainActivity的viewModel值（点击的播放列表）
            List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
            if (mp3Infos != null) {
                int size = mp3Infos.size();
                //上一首的position（oldPosition - 1）小于0则归最大长度-1
                int newPosition = oldPosition - 1 < 0 ? size - 1 : oldPosition - 1;
                Intent serviceIntent = new Intent(this, MusicService.class);
                Mp3Info mp3Info = mp3Infos.get(newPosition);
                serviceIntent.putExtra("url", mp3Info.getUrl());
                serviceIntent.putExtra("title", mp3Info.getTitle());
                serviceIntent.putExtra("artist", mp3Info.getArtist());
                //重新设置mainActivity的viewModel值（播放的位置）
                mainMusicListViewModel.getPositionLiveData().setValue(newPosition);
                //启动播放服务
                startService(serviceIntent);
            }
        }
    }

    /**
     * 按照乱序position播放上一首
     */
    private void lastRandom() {
        //获取mainActivity的viewModel值（当前播放列表）
        List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
        if (mp3Infos != null) {
            //获取mainActivity的viewModel值（当前播放的位置）
            Integer nowPosition = mainMusicListViewModel.getPositionLiveData().getValue();
            if (nowPosition != null) {
                //当前播放位置处于乱序position列表的位置
                Integer oldPosition = randomMap.get(nowPosition);
                if (oldPosition != null) {
                    //播放列表长度
                    int size = mp3Infos.size();
                    //上一首的position（oldPosition - 1）小于0则归最大长度-1
                    int newPosition = oldPosition - 1 < 0 ? size - 1 : oldPosition - 1;
                    //取实际播放列表位置
                    int lastPosition = positions.get(newPosition);
                    Intent serviceIntent = new Intent(this, MusicService.class);
                    Mp3Info mp3Info = mp3Infos.get(lastPosition);
                    //传送url给service播放
                    serviceIntent.putExtra("url", mp3Info.getUrl());
                    serviceIntent.putExtra("title", mp3Info.getTitle());
                    serviceIntent.putExtra("artist", mp3Info.getArtist());
                    //设置mainActivity的viewModel值（播放的位置）
                    mainMusicListViewModel.getPositionLiveData().setValue(lastPosition);
                    //启动播放服务
                    startService(serviceIntent);
                }
            }
        }
    }

    /**
     * 播放上一首音乐（考虑播放模式）
     */
    private void lastMode() {
        //获取mainActivity的viewModel值（播放模式）
        Integer mode = mainMusicListViewModel.getModeLiveData().getValue();
        if (mode != null) {
            switch (mode) {
                case LIST_XUN:
                case ONE_XUN:
                    //单曲循环和列表循环，正常播放上一首
                    last();
                    break;
                case SUI_XUN:
                    //随机循环，按照乱序position播放上一首
                    lastRandom();
                    break;
                default:
            }
        }
    }

    /**
     * 播放下一首音乐
     */
    private void next() {
        //获取mainActivity的viewModel值（播放的位置）
        Integer oldPosition = mainMusicListViewModel.getPositionLiveData().getValue();
        if (oldPosition != null) {
            //获取mainActivity的viewModel值（点击的播放列表）
            List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
            if (mp3Infos != null) {
                if (positions != null && randomMap != null) {
                    int size = mp3Infos.size();
                    //下一首的position（oldPosition + 1）等于列表长度则归0
                    int newPosition = oldPosition + 1 == size ? 0 : oldPosition + 1;
                    Intent serviceIntent = new Intent(this, MusicService.class);
                    Mp3Info mp3Info = mp3Infos.get(newPosition);
                    serviceIntent.putExtra("url", mp3Info.getUrl());
                    serviceIntent.putExtra("title", mp3Info.getTitle());
                    serviceIntent.putExtra("artist", mp3Info.getArtist());
                    //设置mainActivity的viewModel值（播放的位置）
                    mainMusicListViewModel.getPositionLiveData().setValue(newPosition);
                    //启动播放服务
                    startService(serviceIntent);
                }
            }
        }
    }

    /**
     * 按照乱序position播放下一首
     */
    private void nextRandom() {
        //获取mainActivity的viewModel值（当前播放列表）
        List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
        if (mp3Infos != null) {
            //获取mainActivity的viewModel值（当前播放的位置）
            Integer nowPosition = mainMusicListViewModel.getPositionLiveData().getValue();
            if (nowPosition != null) {
                if (positions != null && randomMap != null) {
                    //当前播放位置处于乱序position列表的位置
                    Integer oldPosition = randomMap.get(nowPosition);
                    if (oldPosition != null) {
                        //播放列表长度
                        int size = mp3Infos.size();
                        //下一首在乱序position列表的位置（oldPosition + 1）等于列表长度则归0
                        int newPosition = oldPosition + 1 == size ? 0 : oldPosition + 1;
                        //取实际播放列表位置
                        int nextPosition = positions.get(newPosition);
                        Intent serviceIntent = new Intent(this, MusicService.class);
                        Mp3Info mp3Info = mp3Infos.get(nextPosition);
                        serviceIntent.putExtra("url", mp3Info.getUrl());
                        serviceIntent.putExtra("title", mp3Info.getTitle());
                        serviceIntent.putExtra("artist", mp3Info.getArtist());
                        //设置mainActivity的viewModel值（播放的位置）
                        mainMusicListViewModel.getPositionLiveData().setValue(nextPosition);
                        //启动播放服务
                        startService(serviceIntent);
                    }
                }
            }
        }
    }

    /**
     * 播放下一首音乐（考虑播放模式）
     */
    private void nextMode() {
        //获取mainActivity的viewModel值（播放模式）
        Integer mode = mainMusicListViewModel.getModeLiveData().getValue();
        if (mode != null) {
            switch (mode) {
                case LIST_XUN:
                case ONE_XUN:
                    //单曲循环和列表循环，正常播放下一首
                    next();
                    break;
                case SUI_XUN:
                    //随机循环，按照乱序position播放下一首
                    nextRandom();
                    break;
                default:
            }
        }
    }

    /**
     * 切换播放模式
     */
    public void switchMode() {
        Integer mode = mainMusicListViewModel.getModeLiveData().getValue();
        if (mode != null) {
            //通过模式值+1改变模式
            mode = mode + 1;
            //模式值>2则归0（0到2三种模式）
            if (mode > SUI_XUN) {
                mode = LIST_XUN;
            }
            mainMusicListViewModel.getModeLiveData().setValue(mode);
            switch (mode) {
                case LIST_XUN:
                case SUI_XUN:
                    //随机循环和列表循环，关闭无限循环
                    if (mService != null) {
                        if (mService.isLooping()) {
                            mService.setLooping(false);
                        }
                    }
                    break;
                case ONE_XUN:
                    //单曲循环，开启无限循环
                    if (mService != null) {
                        if (!mService.isLooping()) {
                            mService.setLooping(true);
                        }
                    }
                    break;
                default:
            }
        }
    }

}